#include<iostream>
#include<sys/epoll.h>
#include"Log.hpp"
#include<unistd.h>
#include<errno.h>
#include<string.h>


class Epoller
{
public:
    const static int defaultepfd=-1;
    const static int size=128;
    Epoller():_epfd(defaultepfd)
    {}
    void InitEpoller()
    {
        _epfd=epoll_create(size);
        if(_epfd==defaultepfd)
        {
            lg.LogMessage(Fatal,"create_epoll error,%s : %d\n",strerror(errno),errno);
            exit(4);
        }
        lg.LogMessage(Info,"create_epoll success,%d\n",_epfd);
    }
    void Add(int sockfd,uint32_t event)
    {
        struct epoll_event ev;
        ev.events=event;
        ev.data.fd=sockfd;
        int n=epoll_ctl(_epfd,EPOLL_CTL_ADD,sockfd,&ev);
        if(n<0)
        {
            lg.LogMessage(Error,"epoll_ctl add error,%s : %d\n",strerror(errno),errno);
        }
    }
    int Wait(struct epoll_event *revs,int maxevents,int timeout)
    {
        int n=epoll_wait(_epfd,revs,maxevents,timeout);
        return n;
    }
    void DelEvent(int fd)
    {
        int n=epoll_ctl(_epfd,EPOLL_CTL_DEL,fd,nullptr);
        if(n<0)
        {
            lg.LogMessage(Error,"epoll_ctl close error,%s : %d\n",strerror(errno),errno);
        }
    }
    ~Epoller()
    {
        if(_epfd>=0)
        {
            close(_epfd);
            lg.LogMessage(Info,"epoll close success,%d\n",_epfd);
        }
    }
private:
    int _epfd;
};